package com.kzj.mls.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.kzj.mls.R;
import com.kzj.mls.beans.CityBean;
import com.kzj.mls.fragment.OrderFragment;
import com.kzj.mls.fragment.UserAboutFragment;
import com.kzj.mls.fragment.MainFragment;
import com.kzj.mls.global.App;
import com.kzj.mls.viewPagerTransforms.*;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by xyg on 2015/9/30.
 */
public class MainActivity extends GBaseActivity implements ViewPager.OnPageChangeListener {
    private ViewPager viewpage;
    private LinearLayout linearlayout_bottom_bar, linearLayout_order, linearLayout_my, linearLayout_service;
    private ImageView imageview_service;
    private TextView textview_service;
    private ImageView imageview_order;
    private TextView textview_order;
    private ImageView imageview_my;
    private TextView textview_my;
    private TabFragmentPagerAdapter tabFragmentPagerAdapter;
    public Map<String, Fragment> fragmentsMap = new HashMap<String, Fragment>();
    private FragmentManager manager;
    Fragment fragment1;
    Fragment fragment2;
    Fragment fragment3;
    private LocationClient locClient;
    public BDLocationListener myListener = new MyLocationListener();
    private double latitude, longitude;
    private static final ArrayList<TransformerItem> TRANSFORM_CLASSES;
    public static boolean IsChecked = false;
    private long exitTime;

    static {

        TRANSFORM_CLASSES = new ArrayList<>();
        TRANSFORM_CLASSES.add(new TransformerItem(DefaultTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(AccordionTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(BackgroundToForegroundTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(DepthPageTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(ForegroundToBackgroundTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(CubeInTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(CubeOutTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(FlipHorizontalTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(FlipVerticalTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(RotateDownTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(RotateUpTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(StackTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(TabletTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(ZoomInTransformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(ZoomOutTranformer.class));
        TRANSFORM_CLASSES.add(new TransformerItem(ZoomOutSlideTransformer.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentViewFor720_1280(R.layout.activity_main);
        findViewByIds();
        initDatas();
    }

    @Override
    protected void findViewByIds() {
        viewpage = (ViewPager) findViewById(R.id.viewPager);
        linearlayout_bottom_bar = (LinearLayout) findViewById(R.id.linearlayout_bottom_bar);
        linearlayout_bottom_bar.setOnClickListener(this);
        linearLayout_order = (LinearLayout) findViewById(R.id.linearLayout_order);
        linearLayout_order.setOnClickListener(this);
        linearLayout_my = (LinearLayout) findViewById(R.id.linearLayout_my);
        linearLayout_my.setOnClickListener(this);
        linearLayout_service = (LinearLayout) findViewById(R.id.linearLayout_service);
        linearLayout_service.setOnClickListener(this);
        imageview_service = (ImageView) findViewById(R.id.imageview_service);
        textview_service = (TextView) findViewById(R.id.textview_service);
        imageview_order = (ImageView) findViewById(R.id.imageview_order);
        textview_order = (TextView) findViewById(R.id.textview_order);
        imageview_my = (ImageView) findViewById(R.id.imageview_my);
        textview_my = (TextView) findViewById(R.id.textview_my);

    }

    @Override
    protected void initDatas() {
        manager = getSupportFragmentManager();
        initFragments();
        EventBus.getDefault().register(this);
        tabFragmentPagerAdapter = new TabFragmentPagerAdapter(manager);
        viewpage.setAdapter(tabFragmentPagerAdapter);
        viewpage.setOffscreenPageLimit(3);
        viewpage.setOnPageChangeListener(this);
        // showLeftAddress(View.VISIBLE, "广州");
        setTopTitle("接单");
//        try {
//            viewpage.setPageTransformer(true,TRANSFORM_CLASSES.get(5).clazz.newInstance());
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
        initLocation();
        locClient.start();
        UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
            @Override
            public void onUpdateReturned(int updateStatus, UpdateResponse updateResponse) {
                switch (updateStatus) {
                    case UpdateStatus.Yes: // has update
                        UmengUpdateAgent.showUpdateDialog(MainActivity.this, updateResponse);
                        break;
                    case UpdateStatus.No: // has no update
                        if (IsChecked)
                            Toast.makeText(MainActivity.this, "当前版本为最新版本", Toast.LENGTH_SHORT).show();
                        break;
                    case UpdateStatus.NoneWifi: // none wifi
                        if (IsChecked)
                            Toast.makeText(MainActivity.this, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
                        break;
                    case UpdateStatus.Timeout: // time out
                        if (IsChecked)
                            Toast.makeText(MainActivity.this, "连接超时", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
        UmengUpdateAgent.update(this);
    }

    /**
     * @param cityBean
     */
    public void onEventMainThread(CityBean cityBean) {
//        showLeftAddress(View.VISIBLE, cityBean.getCity_name());
//        App.getInstance().setCity(cityBean.getCity_name());
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        locClient = new LocationClient(App.getInstance().getApplicationContext());     //声明LocationClient类
        locClient.setLocOption(option);
        locClient.registerLocationListener(myListener);    //注册监听函数
    }

    @Override
    protected void fillArrayInListView() {

    }

    private void initFragments() {
        fragment1 = new MainFragment();
        fragment2 = new OrderFragment();
        fragment3 = new UserAboutFragment();


        fragmentsMap.put("1", fragment1);
        fragmentsMap.put("2", fragment2);
        fragmentsMap.put("3", fragment3);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                changeDefaultStatus(linearLayout_service);
                imageview_service.setBackgroundResource(R.drawable.icon_service_pressed);
                textview_service.setTextColor(getResources().getColor(R.color.color_f875a3_red));
                setTopTitle("接单");
                break;
            case 1:
                changeDefaultStatus(linearLayout_order);
                imageview_order.setBackgroundResource(R.drawable.icon_order_pressed);
                textview_order.setTextColor(getResources().getColor(R.color.color_f875a3_red));
                setTopTitle("订单");
                break;
            case 2:
                changeDefaultStatus(linearLayout_my);
                imageview_my.setBackgroundResource(R.drawable.icon_my_pressed);
                textview_my.setTextColor(getResources().getColor(R.color.color_f875a3_red));
                setTopTitle("我的");
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    class TabFragmentPagerAdapter extends FragmentStatePagerAdapter {


        public TabFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment ft = null;
            switch (position) {
                case 0:

                    ft = fragmentsMap.get("1");
                    break;
                case 1:
                    ft = fragmentsMap.get("2");
                    break;
                case 2:
                    ft = fragmentsMap.get("3");
                    break;
                default:
                    break;
            }
            return ft;
        }

        @Override
        public int getCount() {
            return fragmentsMap.size();
        }


    }

    private static final class TransformerItem {

        final String title;
        final Class<? extends ViewPager.PageTransformer> clazz;

        public TransformerItem(Class<? extends ViewPager.PageTransformer> clazz) {
            this.clazz = clazz;
            title = clazz.getSimpleName();
        }

        @Override
        public String toString() {
            return title;
        }

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.linearLayout_service:
                viewpage.setCurrentItem(0, false);
                changeDefaultStatus(linearLayout_service);
                imageview_service.setBackgroundResource(R.drawable.icon_service_pressed);
                textview_service.setTextColor(getResources().getColor(R.color.color_f875a3_red));
                setTopTitle("接单");
                break;
            case R.id.linearLayout_order:
                viewpage.setCurrentItem(1, false);
                changeDefaultStatus(linearLayout_order);
                imageview_order.setBackgroundResource(R.drawable.icon_order_pressed);
                textview_order.setTextColor(getResources().getColor(R.color.color_f875a3_red));
                setTopTitle("订单");
                break;
            case R.id.linearLayout_my:
                viewpage.setCurrentItem(2, false);
                changeDefaultStatus(linearLayout_my);
                imageview_my.setBackgroundResource(R.drawable.icon_my_pressed);
                textview_my.setTextColor(getResources().getColor(R.color.color_f875a3_red));
                setTopTitle("我的");
                break;

            default:
                break;
        }
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            if (location == null) {
                return;
            }
            if (location.getCity() != null) {
                App.getInstance().setLatitude(location.getLatitude() + "");
                App.getInstance().setLongitude(location.getLongitude() + "");
                App.getInstance().setCity(location.getCity());
                App.getInstance().setLocationCity(location.getCity());
                locClient.stop();
            }
           /* StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息

            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());

            if (location.getLocType() == BDLocation.TypeNetWorkLocation || location.getLocType() == BDLocation.TypeGpsLocation) {

                // MapStatusUpdate描述地图将要发生的变
                // MapStatusUpdateFactory生成地图将要反生的变
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            } else {

            }*/
        }
    }

    private void changeDefaultStatus(View v) {
        imageview_service.setBackgroundResource(R.drawable.icon_service_normal);
        textview_service.setTextColor(getResources().getColor(R.color.color_646464_black));
        imageview_order.setBackgroundResource(R.drawable.icon_order_normal);
        textview_order.setTextColor(getResources().getColor(R.color.color_646464_black));
        imageview_my.setBackgroundResource(R.drawable.icon_my_normal);
        textview_my.setTextColor(getResources().getColor(R.color.color_646464_black));
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);       //统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000)  //System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                MobclickAgent.onKillProcess(this);
                MobclickAgent.onKillProcess(this);
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
